var netWork = require('../../../utils/netWork.js');
var utils = require('../../../utils/util.js');
var api = require('../../../utils/api.js');
var apiCode = require('../../../utils/openApiCode.js');
const app = getApp();
import {authUserPhone} from "../../../utils/publicMethods";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topHeight: 0, //顶部高度
    imagesUrl: getApp().globalData.imagesUrl,
    prizeList: [],
    ani: 0, //动画是否执行
    isShowModalRule: false, //是否显示活动规则
    isShowModalAuth: false, //是否显示授权按钮
    isShowModalPubNum: false, //顶部关注公众号
    getPhone: false, //是否已拉取手机号
    choosePrize: "", //勾选的产品
    source: "", //来源

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    api.showLoading('正在加载中...')
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    this.setData({
      topHeight: topHeight,
      source: options.source
    });
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    if (wx.getStorageSync('getPhone')) {
      this.setData({
        getPhone: wx.getStorageSync('getPhone'),
      })
    }
    let newList = []; //构建新数组，增加status(是否勾选)
    let prizeL = JSON.parse(options.prizeInfo);
    if (prizeL) {
      //先判断是否为二选一
      if (prizeL.schemeList != null && prizeL.schemeList.length > 0) { //二选一
        for (var item in prizeL.schemeList) {
          if (item.prizeType != 8) {
            var newItem = prizeL.schemeList[item];
            newItem['status'] = false;
            newList.push(newItem)
          }
        }
        this.setData({
          type: utils.getType(newList.length),
          prizeList: newList,
          prizeOrderId: prizeL.prizeOrderId
        })
      } else { //非二选一
        newList.push(prizeL);
        this.setData({
          prizeList: newList
        })
      }

    }
    // 获取jsCode
    this.updateJSCode();
  },
  updateJSCode() {
    wx.login({
      success: res => {
        console.log("[onLoad--wx.login]" + res.code);
        if (res.code) {
          wx.setStorageSync('code', res.code)
        } else {
          console.log("获取jsCode失败" + res.errMsg);
        }
      }
    });
  },
  onReady: function () {
    
  },

  /**
   * 勾选实物
   * @param {*} e 
   */
  onclick: function (e) {
    var arr = this.data.prizeList; //声明的数组
    var index = e.currentTarget.dataset.index; //当前数组的索引下标
    for (var item in arr) {
      if (item == index) {
        arr[item].status = true;
        //把选中的奖品存在data
        this.setData({
          choosePrize: arr[item]
        })

      } else {
        arr[item].status = false;
      }
    }
    this.setData({
      prizeList: arr
    })
  },
  //获取用户地理位置，然后进行兑奖
  getLoca: function () {
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        //存入地址
        wx.setStorageSync('latitude', res.latitude);
        wx.setStorageSync('longitude', res.longitude);
        wx.setStorageSync('speed', res.speed);
        wx.setStorageSync('accuracy', res.accuracy);
        //兑奖
        this.checkChoose();
      },
      fail: res => {
        console.log('[wx.getLocation===res.errMsg]' + JSON.stringify(res.errMsg))
        if (res.errMsg) {
          that.setData({
            isShowModalAuth: true,
            authText:"为了保证正常获取奖励，现需获取您的地理位置",
            isSetting: 1
          })
        }
      }
    })
  },
  openSetting() {
    this.setData({
      isShowModalAuth: false
    })
    api.putOpenSetting();
  },
  /**
   * 领取奖励
   */
  secondLQ() {
    if (this._freshing) return
    this._freshing = true;
    if (wx.getStorageSync('getLocationStyle') == "prize") { //兑奖时时拉取
      this.getLoca();
      this._freshing = false;
    } else {
      this.checkChoose();
      this._freshing = false;
    }
  },
  /**
   * 判断是否选择奖品
   */
  checkChoose: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    if (this.data.prizeList.length != 1) {
      if (this.data.choosePrize == "") {
        setTimeout(function () {
          wx.showToast({
            title: '请勾选您想要领取的奖品',
            icon: 'none',
            duration: 2500
          })
        }, 500);
        return;
      }
      wx.redirectTo({ //跳转到 领取信息填写页面
        url: '../../receiptInfo/receiptInfo?source=' + this.data.source + '&prizeInfo=' + JSON.stringify(this.data.choosePrize)
      })
    } else {
      if (this.data.prizeList[0].prizeType == 1) {
        //红包
        this.revicePrize();
      } else {
        wx.redirectTo({ //跳转到 领取信息填写页面
          url: '../../receiptInfo/receiptInfo?source=' + this.data.source + '&prizeInfo=' + JSON.stringify(this.data.prizeList[0])
        })
      }
    }
  },
  /**
   * 点击领取,进行兑奖
   */
  revicePrize: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    api.showLoading('正在加载中...')
    const that = this;
    //兑奖红包
    //兑奖-实物奖
    netWork.POST('receiveWxRedBag', {
      data: {
        userId: wx.getStorageSync('userId'),
        prizeOrderId: that.data.prizeList[0].prizeOrderId,
        prizeId: that.data.prizeList[0].prizeId,
        positioningStyle: wx.getStorageSync('positioningStyle'),
        positioningType: wx.getStorageSync('positioningType'),
        latitude: wx.getStorageSync('latitude'),
        longitude: wx.getStorageSync('longitude'),
        speed: wx.getStorageSync('speed'),
        accuracy: wx.getStorageSync('accuracy'),
        source: that.data.source, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
      },
      success: function (res) {
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          wx.redirectTo({
            url: '../../success/success?source=1&prizeOrderId='+that.data.prizeList[0].prizeOrderId,
          })
        } else {
          wx.redirectTo({
            url: '../../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
          })
        }

      },
      fail: function () {
        wx.redirectTo({
          url: '../../prompt/prompt?retCode=' + apiCode.DRAWFAIL.code + '&retMsg=' + apiCode.DRAWFAIL.msg,
        })
      }
    });
  },
  /**
   *查询是否关注公众号
   */
  queryIsFollow: function () {
    const that = this;
    netWork.POST('searchUserInfo', {
      data: {
        userId: wx.getStorageSync('userId')
      },
      success: function (res) {
        api.cancelLoading();
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          if (res.data.data.isFollow == 1) {//关注
           //跳转中奖记录
           wx.redirectTo({
            url: '../../prizeRecord/prizeRecord',
          })
          } else {//未关注，引导关注
            wx.navigateTo({
              url: '../../officialAccount/officialAccount',
            })
          }
          
        }else{//失败，暂时不按未关注处理

        }
      },
      fail: function () {
        wx.redirectTo({
          url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        })
      }
    });
  },
  /**
   * 跳转中奖记录页面
   */
  showPrizeRecord: function () {
    this.queryIsFollow();
  },
  /**
   * 更多活动， 跳转第三方小程序
   */
  showMore: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    wx.navigateToMiniProgram({
      appId: api.thirdAppId,
    })
  },
  /**
   * 获取手机号
   * @param {*} e 
   */
  getPhoneNumber: async function (e) {
    var that = this;
    if (e.detail.encryptedData != undefined) {
      that.setData({ //同意
        isShowModalAuth: false
      })
      wx.setStorageSync('getPhone', true)
      this.setData({
        getPhone: true
      })
      //更新用户信息
      let res = await authUserPhone(e);
      if (wx.getStorageSync('getLocationStyle') == "prize") { //兑奖时时拉取
        this.getLoca();
      } else {
        this.secondLQ();
      }

      //同意获取手机号
      // if (that.data.isFollow != 1) { //已关注过，直接领取
      //   //未关注过，先引导关注
      //   let scene = getApp().globalData.scene;
      //   console.log("场景"+scene);
      //   // 当小程序从扫小程序码场景（ 场景值1047， 场景值1124） 打开时
      //   // 当小程序从聊天顶部场景（ 场景值1089） 中的「 最近使用」 内打开时， 若小程序之前未被销毁， 则该组件保持上一次打开小程序时的状态
      //   // 当从其他小程序返回小程序（ 场景值1038） 时， 若小程序之前未被销毁， 则该组件保持上一次打开小程序时的状态
      //   //开发版小程序从扫二维码（场景值 1011）打开 — 体验版小程序打开
      //   if (scene == 1047 || scene == 1124 || scene == 1011 || scene == 1038 || scene == 1089) {
      //     //展示关注公众号组件
      //     that.setData({
      //       isShowModalPubNum: true
      //     })
      //   }
      //   return;
      // }
      //已关注，直接领奖

    } else {
      console.log("拒绝授权");
      that.setData({ //显示拒绝授权提示层
        isShowModalAuth: true,
        authText:"为了保证正常获取奖励，现需获取您的手机号码",
        isPhone: '1'
      })
    }
  },
  /**
   * 更新用户信息
   */
  updateUserInfo(encryptedData, iv) {
    const that = this;
    netWork.POST('updateUserInfo', {
      data: {
        userId: wx.getStorageSync('userId'),
        encryptedData: encodeURIComponent(encryptedData),
        iv: encodeURIComponent(iv),
        jsCode: wx.getStorageSync('code')
      },
      success: function (res) {
        if (res.data.retCode == undefined) {
          // wx.redirectTo({
          //   url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          // })
        }
        if (res.data.retCode == '0000') {
          wx.setStorageSync('userPhone', res.data.data.phone);
          wx.setStorageSync('nickName', res.data.data.nickName);
        } else {
          //跳转温馨提示页面
          // wx.redirectTo({
          //   url: '../../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
          // })
        }
      },
      fail: function (res) {
        //跳转温馨提示页面
        // wx.redirectTo({
        //   url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        // })
      }
    });
  },
  /**
   * 显示活动规则
   */
  showRule: function () {
    console.log('show')
    this.setData({
      isShowModalRule: true,
      ani: 0
    })
  },
  closeMask: function () {
    this.setData({
      isShowModalRule: false, //是否显示活动规则
      isShowModalPubNum: false, //顶部关注公众号
    })
    if (!this.data.isShowModalAuth) {
      this.revicePrize(); //兑奖
    }
  },
  /**
   * 关闭活动规则
   */
  clickClose: function () {
    this.setData({
      ani: 1
    })
    const that = this;
    setTimeout(function () {
      that.setData({
        isShowModalRule: false
      })
    }, 180);
  },
  onShow(){
    try {
        if (wx.onNeedPrivacyAuthorization) {
            wx.onNeedPrivacyAuthorization(resolve => {
                this.selectComponent('#privacyPopup').show();//这里是让组件弹窗显示
                this.selectComponent('#privacyPopup').data.parentPageInfo = this;
                this.resolvePrivacyAuthorization = resolve
            })
        }
    } catch (error) {
        console.info(error)
    }
  }
})